import React, { useContext, useMemo, useState } from 'react'
import Myback from './conponents/Myback'
import Ctx from '../store/Ctx'
import { Tabs, ProductCard, Tag, Button } from 'react-vant'

//个人中心 计算订阅个数 收藏和订阅切换
export default function My(props) {

  //获取数据
  let obj = useContext(Ctx)

  //计算个数 全部 订阅的个数
  let changeSub = useMemo(() => {
    //收敛 求和 扁平化数组
    return obj.datalist.reduce((p, n) => {
      if (n.sub) { //123类型 订阅的个数
        return p + 1
      }
      return p
    }, 0)
  }, [obj.datalist])

  //计算个数 小说和儿童 订阅的个数
  let changeXe = useMemo(() => {
    return obj.datalist.reduce((p, n) => {
      if (n.sub && n.typeId !== 1) {
        return p + 1
      }
      return p
    }, 0)
  }, [obj.datalist])

  let [index, setIndex] = useState(0) //0是收藏 1是订阅

  let newIndex = useMemo(() => {
    return obj.datalist.filter(item => {
      if (index == 0) {
        return item.collec
      } else {
        return item.sub
      }
    })
  }, [obj.datalist, index])

  return (
    <div>
      {/* 导航栏 */}
      <Myback title={'个人中心'} leftText={true}></Myback>
      <p>全部订阅的个数:{changeSub}</p>
      <p>小说和儿童订阅的个数:{changeXe}</p>

      {/* 标签页 */}
      <div>
        <Tabs onChange={(e) => {
          setIndex(e)
        }}>
          {['收藏', '订阅'].map(item => (
            <Tabs.TabPane key={item} title={item}>
            </Tabs.TabPane>
          ))}
        </Tabs>
      </div>

      {/* 商品卡片 渲染数据 */}
      <div style={{ height: 'calc(100vh - 200px)', overflowY: 'scroll' }}>
        {
          newIndex.map(item => {
            return <ProductCard onClick={()=>{
              props.history.push({
                pathname:'/details',
                state:item.id
              })
            }}
              key={item.id}
              num={<>
                {
                  index ? <Button round size='small' onClick={() => {
                    obj.dispatch({
                      type: 'change_sub',
                      payload: item.id
                    })
                  }}>取消订阅</Button > : <Button round size='small' 
                  onClick={(e) => {
                    //阻止冒泡
                    e.stopPropagation()
                    //切换收藏的状态
                    obj.dispatch({
                      type: 'change_collec',
                      payload: item.id
                    })
                  }}>取消收藏</Button>
                }
              </>}
              desc={item.ms}
              title={item.title}
              thumb={item.img}
            />
          })
        }
      </div>

    </div>
  )
}
